const DB = require('../tools/mysql')
const request = require('sync-request')
let appid = 'wxf91ef0b115ag2df2'
let secret = '41c83f1520280sd34a0c5b1f567e1de5'

module.exports = async ctx => {
  const res = request('GET', `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${ctx.request.body.code}&grant_type=authorization_code`)
  const openid = JSON.parse(res.getBody('utf-8')).openid
  const exit = await DB('user').where('openid', openid)
  if (exit.length === 0 ) {
    await DB('user').insert({ name: ctx.request.body.name, openid: openid, img: ctx.request.body.img })
    ctx.body = { code: false }
  } else {
    const list = await DB('user').where('code', 1).select('openid')
    for (var i = 0; i < list.length; i++) {
      if (list[i].openid == openid) {
        ctx.body = { code: true }
        return
      }
    }
    ctx.body = { code: false }
  }
}